#include "DXUT.h"
#include "UtilityFunctions.h"

std::wstring UtilityFunction::strtowstr(const std::string &str)
{
	// Convert an ASCII string to a Unicode String
	std::wstring wstrTo;
	wchar_t *wszTo = new wchar_t[str.length() + 1];
	wszTo[str.size()] = L'\0';
	MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
	wstrTo = wszTo;
	delete[] wszTo;
	return wstrTo;
}

std::string UtilityFunction::wstrtostr(const std::wstring &wstr)
{
	// Convert a Unicode string to an ASCII string
	std::string strTo;
	char *szTo = new char[wstr.length() + 1];
	szTo[wstr.size()] = '\0';
	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
	strTo = szTo;
	delete[] szTo;
	return strTo;
}

bool UtilityFunction::ListAllFilesInFolder(TCHAR* strDir, TCHAR* strFileNamePattern, CGrowableArray<std::wstring>& FileNameArr)
{
	if(!strDir) 
	{
#ifdef _DEBUG
		OUTPUTERRORINFO;
#endif
			return false;
	}
	WIN32_FIND_DATA ffd;
	HANDLE hFind = INVALID_HANDLE_VALUE;

	TCHAR sFileDir[MAX_PATH];
	memset(sFileDir,0,sizeof(TCHAR)*MAX_PATH);
	// Prepare string for use with FindFile functions.  First, copy the
	// string to a buffer, then append '\*' to the directory name.
	wcscpy(sFileDir, strDir);
	wcscat(sFileDir, L"\\");
	if(strFileNamePattern)
		wcscat(sFileDir, strFileNamePattern);

	// Find the first file in the directory.
	hFind = FindFirstFile(sFileDir, &ffd);
	if (INVALID_HANDLE_VALUE == hFind) 
	{
		printf("No EM cubemap file found!\n");
		return false;
	} 
	// List all the files in the directory with some info about them.
	do
	{
		std::wstring filename;
		filename.assign(ffd.cFileName);
		FileNameArr.Add(filename);
	}
	while (FindNextFile(hFind, &ffd) != 0);

	FindClose(hFind);
	return true;
}

// MC Function Definitions
void UtilityFunction::ComputeStep1dCDF(float *f, int nSteps, float *c,float *cdf) 
{
		// Compute integral of step function at $x_i$
		int i;
		cdf[0] = 0.0f;
		for (i = 1; i < nSteps+1; ++i)
			cdf[i] = cdf[i-1] + f[i-1] / nSteps;
		// Transform step function integral into cdf
		*c = cdf[nSteps];
		for (i = 1; i < nSteps+1; ++i)
			cdf[i] /= *c;
}